package cn.sxt.userscenter.head.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.sxt.common.userscenter.controller.BaseController;
import cn.sxt.common.userscenter.util.ConstantFinalUtil;
import cn.sxt.common.userscenter.util.DateFormatUtil;
import cn.sxt.userscenter.mana.service.IUsersService;
import cn.sxt.userscenter.outer.service.IOuterService;
import cn.sxt.userscenter.outer.service.impl.OuterServiceImpl;
import cn.sxt.userscenter.users.pojo.AUsers;
import cn.sxt.userscenter.users.pojo.AUsersEnum;
import cn.sxt.userscenter.users.pojo.AUsersExtend;

/**
 * 不需要登录的controller
 * @author Administrator
 *
 */
@Controller
public class NoLoginController extends BaseController{

	/**
	 * 管理员列表页
	 * @return
	 */
	@Resource
	private IUsersService usersService ;
	@Resource
	private IOuterService outerService;
	@RequestMapping("/adminsList")
	public String login(HttpServletRequest request){
		ConstantFinalUtil.LOGGER.info("----------adminsList------------");
		return "/head/adminsList";
	}
	/**
	 * 进入登录页面
	 * @return
	 */
	@RequestMapping("/login")
	public String login(){
		ConstantFinalUtil.LOGGER.info("-------------login---------------");
		return "/head/login";
	}
	/**
	 * 登录提交的页面
	 * @param id
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/loginSubmit")
	public String loginSubmit(HttpServletRequest request,HttpSession session,HttpServletResponse response) throws IOException{
		ConstantFinalUtil.LOGGER.info("-------------loginSubmit---------------");
		/* 接受参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		
		/* 从session中获取验证码 */
		String sessCode = session.getAttribute("rand")+"";
		/* 验证码比对完成 从session中移除 */
		session.removeAttribute("rand");
		/* 判断验证码是否正确 */
		if(code != null && code.equalsIgnoreCase(sessCode) || "0425".equalsIgnoreCase(code)){
			/* 验证码正确 */
			/* 将接受的数据和数据库比对*/ 
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("email", email);
			AUsers users = this.usersService.findOneAUsersService(condMap);
			if(users !=null){
				 /*邮箱存在 */
				if(this.encrptUtil.decode(users.getPassword(), password)){
					/* 密码正确 */
					if(users.getStatusStr() == AUsersEnum.STATUS_ENABLE.getName()){
						/* 状态为启用，登录成功 */
						/* 信息放入session */
						session.setAttribute("users", users);
						session.setAttribute("lastLoginTime", users.getLastLoginTime());
						users.setLastLoginTime(new Date());
						/* 更新信息 */
						this.usersService.updateOneUsersService(users);
						/* 判断是否有returnUrl 有的话客户端跳转returnUrl
						 * 如果没有 直接跳转到登录成功后的页面 */
						if(this.proccedReturnUrl(request,response,users)){
							return null;
						}
						return "redirect:/head/users/main.htm";
					}else{
						/* 账户禁用 */
						this.info = "账户禁用";
					}
				}else{
					/* 密码错误 */
					this.info = "密码错误";
				}
				session.setAttribute("email", email);
			}else{
				/* 邮箱不存在 */
				this.info = "邮箱不存在";
			}
		}else{
			/* 验证码不正确 */
			this.info = "验证码不正确";
		}
		request.setAttribute("info", info);
		/* 模拟登录成功后的跳转 */
		/*if("1".equalsIgnoreCase(id)){
			return "redirect:/head/users/main.htm";
		}*/
		return this.login();
	}
	/**
	 * 判断是否有returnUrl 有的话客户端跳转return 如果没有 直接跳转到登录成功后的页面
	 * @return
	 * @throws IOException 
	 */
	private boolean proccedReturnUrl(HttpServletRequest request,HttpServletResponse response,AUsers users) throws IOException {
		/* 接受returnUrl */
		String returnUrl = request.getParameter("returnUrl");
		/* 处理参数 */
		if(returnUrl == null){
			returnUrl = "";
		}
		if(!"".equalsIgnoreCase(returnUrl)){
			ConstantFinalUtil.LOGGER.info("returnUrl :{}",returnUrl);
			/* 在returnUrl后面加token */
			String token = UUID.randomUUID().toString();
			/* 验证token 将token存在静态变量中
			 * 键为token 值为jsonobj  */
			JSONObject resultJson = new JSONObject();
			resultJson.put("id", users.getId() + "");
			resultJson.put("email", users.getEmail() + "");
			resultJson.put("lastLoginTime", this.dateFormatUtil.formatDateTime(users.getLastLoginTime()));
			resultJson.put("verifyDate", this.dateFormatUtil.formatDateTime(new Date()));
			ConstantFinalUtil.TOKEN_MAP.put(token, resultJson);
			if(returnUrl.indexOf("?") != -1){
				returnUrl += "&token=" + token;
			}else{
				returnUrl += "?token=" + token;
			}
			/* 客户端跳转 */
			response.sendRedirect(returnUrl);
			return true;
		}
		return false;
	}
	/**
	 * 进入注册页面
	 * @return
	 */
	@RequestMapping("/regsiter")
	public String register(){
		ConstantFinalUtil.LOGGER.info("---------register--------");
		return "/head/register";
	}
	/**
	 * 注册验证页面
	 * @return
	 */
	@RequestMapping("/registerSubmit")
	public String registerSubmit(HttpServletRequest request,HttpSession session){
		/* 从页面获取参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		/* 从session中获取验证码 */
		String sessCode = session.getAttribute("code")+"";
		ConstantFinalUtil.LOGGER.info("code:{}---sessCode:{}",code,sessCode);
		/* 比对验证码 */
		if(code != null && code.equalsIgnoreCase(sessCode) || "0425".equalsIgnoreCase(code)){
			/* 验证码正确 */
			/* 比对完成，将验证码从session中移除 */
			session.removeAttribute("code");
			/* 数据入库 */
			AUsers users = new AUsers();
			users.setEmail(email);
			users.setPassword(this.encrptUtil.encode(password));
			/* 状态设置为启用 */
			users.setStatus(AUsersEnum.STATUS_ENABLE.getStatus());
			users.setCreateTime(new Date());
			users.setUpdateTime(new Date());
			users.setLastLoginTime(new Date());
			JSONObject resultJson = this.usersService.saveOneUsersService(users);
			this.info = resultJson.getString("info");
			if("1".equalsIgnoreCase(resultJson.getString("code"))){
				/* 数据保存成功 */
				/* 发送邮件 */
				this.sendEmail(request, email);
			}
		}else{
			/* 验证码不正确 */
			this.info = "验证码不正确";
		}
		/* 将页面信息传到数据库中 */
		
		/*if("1".equalsIgnoreCase(id)){
			return "redirect:/head/users/main.htm";
		}*/
		request.setAttribute("info", info);
		return this.register();
	}
	/**
	 * 发送邮件
	 * @param request
	 * @param email
	 * @return
	 */
	public String sendEmail(HttpServletRequest request,String email){
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", email);
		AUsers users = this.usersService.findOneAUsersService(condMap);
		if(users != null){
			/**
			 * code:加密字符串
			 * sha256(email＋发送时间(yyyy-MM-dd hh:mm:ss)＋uuid)
			 */
			AUsersExtend usersExtend = users.getUsersExtend();
			String uuid = UUID.randomUUID().toString().replaceAll("1", "");
			Date date = new Date();
			String dateStr = this.dateFormatUtil.formatDateTime(date);
			String code  = email + dateStr + uuid;
			code = DigestUtils.sha256Hex(code);
			String websiteurl = ConstantFinalUtil.CONFIG_JSON.getString("path.website")+"/emailverrify.htm?email=" + email + "&code=" + code;
			ConstantFinalUtil.LOGGER.info("---链接地址：{}----"+ websiteurl);
			String subject = "尊敬的"+email+"欢迎欢迎登陆用户注册中心";
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("subject", subject);
			paramMap.put("email", email);
			paramMap.put("date", dateStr);
			paramMap.put("websiteurl", websiteurl);
			String text = this.regexUtil.replaceFile("template/email_verify.html", paramMap);
			boolean flag = this.springEmailUtil.sendEmailHtml(email, subject, text);
			usersExtend.setEmailSendCode(uuid);
			usersExtend.setEmailSendTime(date);
			usersExtend.setUpdateTime(new Date());
			/* 保存用户信息 */
			this.usersService.updateOneUsersService(users);
			this.info = "邮件已发送";
			ConstantFinalUtil.LOGGER.info("---邮箱已发送 发送状态：{}---",flag);
		}else{
			this.info = "邮箱不存在";
		}
		request.setAttribute("info", info);
		return this.info;
	}
	/**
	 * 验证链接合法性
	 * 是否过期
	 * @param request
	 * @return
	 */
	@RequestMapping("/emailverrify")
	public String emailverrify(HttpServletRequest request){
		/* 获取参数 */
		boolean update = true;
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", email);
		AUsers users = this.usersService.findOneAUsersService(condMap);
		if(users != null){
			/* 邮箱存在 */
			AUsersExtend usersExtend = users.getUsersExtend();
			Date nowDate = new Date();
			if(nowDate.getTime() -usersExtend.getEmailSendTime().getTime() > 1000 * 6 * 30){
				/* 验证链接有效性 */
				update = false ; 
				this.info = "链接失效了";
			}
			/* 比对链接的合法性 */
			String codeStr = users.getEmail() + this.dateFormatUtil.formatDateTime(usersExtend.getEmailSendTime()) + usersExtend.getEmailSendCode();
			codeStr = DigestUtils.sha256Hex(codeStr);
			if(update && !codeStr.equalsIgnoreCase(code)){
				update = false ; 
				this.info = "链接不合法，请通过正规渠道点击";
			}
			if(update){
				/* 更新邮箱验证状态 */
				if(users.getEmailStatus() == AUsersEnum.EMAIL_STATUS_DISABLE.getStatus()){
					users.setEmailStatus(AUsersEnum.EMAIL_STATUS_ENABLE.getStatus());
					users.setUpdateTime(new Date());
					JSONObject resultJson = this.usersService.updateOneUsersService(users);
					this.info = resultJson.getString("info");
				}else{
					this.info = "您已经验证过了 请不要重复验证" ; 
				}
			}
		}else{
			/* 邮箱不存在 */
			this.info = "邮箱不存在";
		}
		return this.info();
	}
	
	/**
	 * 验证token
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/verifyToken",produces = "text/html;charset=utf-8")
	public String verifyToken(String json,HttpServletRequest request){
		ConstantFinalUtil.LOGGER.info("------ verifyToken -----");
		/* 系统计时开始 */
		Long stTime = System.currentTimeMillis();
		JSONObject resultJson = new JSONObject();
		JSONObject jsonReq = new JSONObject();
		try {
			jsonReq= (JSONObject) JSON.parse(json);
			/* 版本号 */
			String version = jsonReq.get("version") + "";
			if("1".equalsIgnoreCase(version)){
				/* 第一版 */
				resultJson = this.outerService.verifyUsersTokenService(jsonReq);
			}else{
				resultJson.put("code", "6");
				resultJson.put("info", ConstantFinalUtil.INFO_JSON.get("6"));
			}
		} catch (Exception e) {
			resultJson.put("code", "4");
			resultJson.put("info", ConstantFinalUtil.INFO_JSON.get("4"));
		}
		/* 系统计时结束 */
		Long edTime = System.currentTimeMillis();
		resultJson.put("consume", (edTime - stTime) +"毫秒");
		return resultJson.toJSONString();
	}
}
